const SERVICE = require("../../lib/js/service.js");

Page({
  data:{
    imgSrc: SERVICE.imgUrl,
    list: 0,
    // price: { brandPrice: 0, guidePrice: 0, marketPriceSh: 0}
    price: {},
    allSelected: false,
    showNoData: false,
    regDialog: {   //模板数据
      quit: "quit",
      button: "viewDetail"
    },
    showRegDialog: false, //是否显示模板
    isOpenRegDialog: false    //是否有打开过模板
  },
  onLoad(){
   
  },

  onShow(){
    this.getPartsList();
  },

  /*分享*/
  onShareAppMessage(){

  },

  /**
   * @explain partsList 购物车配件列表
   * @pramas thirdCookie 用户标识
   * 
   * **/ 
   getPartsList(){
     wx.showNavigationBarLoading();
     let _this = this;
     SERVICE.POST(SERVICE.URL.partsList,{
       thirdCookie: wx.getStorageSync("thirdCookie")
     },(status,res)=>{
       wx.hideNavigationBarLoading();
       console.log("购物车配件列表:",res);
       if(res.data.status == "success"){
         let list = res.data.result;
         if (list.length > 0){
           for (let i = 0; i < list.length; i++) {
             list[i].selected = false;
             for (let e = 0; e < list[i].count; e++) {
               list[i].list[e].selected = false;
             }
           }
           _this.setData({
             list
           });
         }else{
           _this.setData({
             showNoData: true,
             list: null,
             allSelected: false
           });
         }
       }else{
         wx.showToast({
           title: "获取配件列表失败",
           icon: "none",
           mask: true
         });
       }
     });
   },

  /**
   * @explain 获取一级项
   * 
   * **/  
  getListItem(e){
    let index = e.currentTarget.dataset.index;
    this.getItemSelected({
      type: "all",
      item: index
    });
  },

  /**
   * @explain 获取二级项
   * 
   * **/ 
  getListItemChild(e){
    let id = e.currentTarget.dataset.id, 
      index = e.currentTarget.dataset.index;
    this.getItemSelected({
      type: "one",
      item: index,
      childId: id
    });
  },


  /**
   * @explain 全选
   * 
   * **/
  getAllSelected() {
    let td = this.data;
    this.setData({
      allSelected: !td.allSelected
    });
    this.getSelected(td.allSelected);
  },

  /**
   * @explain 获取项 全选反选
   * @param type 类型 （all 项的全选 one 单选）
   * @pram 
   ***/
  getItemSelected(obj){
    let td_list = this.data.list;
    for (let i = 0; i < td_list.length; i++) {
      if (obj.type === "all" && i === obj.item){
        td_list[i].selected = !td_list[i].selected;
        
        for (let e = 0; e < td_list[i].count; e++) {
          if (td_list[i].selected === false){
            td_list[i].list[e].selected = false;
          }else{
            td_list[i].list[e].selected = true;
          }
         
        }
      } else if (obj.type === "one" && i === obj.item){
        let num = 0;
        for (let e = 0; e < td_list[i].count; e++) {
          if (td_list[i].list[e].id === obj.childId) {
            td_list[i].list[e].selected = !td_list[i].list[e].selected;
          }
          
          if (td_list[i].list[e].selected === true ) {
            // // e + 1 === td_list[i].count ? td_list[i].selected = true : td_list[i].selected = false;
            // if(e + e === 2){
            //   console.log(e);
            //   td_list[i].selected = true;
            // }

            num ++;

            if (num === td_list[i].count){
              td_list[i].selected = true;
            }
          }else{
            td_list[i].selected = false;
          }
        }
      }
      
    }
    this.setData({
      list: td_list
    });
    this.getPrice();
  },



  /**
   * @explain 获取列表 全选反选
   * @param status 全选状态
   ***/
  getSelected(status) {
    let td_list = this.data.list;
    for (let i = 0; i < td_list.length; i++) {
      status == true ? td_list[i].selected = true : td_list[i].selected = false;
      for (let e = 0; e < td_list[i].count; e++) {
        status == true ? td_list[i].list[e].selected = true : td_list[i].list[e].selected = false;
      }
    }
    this.setData({
      list: td_list
    });
    this.getPrice();
  },


  /**
   * @explain 获取价格
   * 
   * **/ 
  getPrice(){
    let td = this.data, td_list = this.data.list;
        td.price.brandPrice = 0;
        td.price.guidePrice = 0;
        td.price.marketPriceSh = 0;
    let num = 0;
    console.log(td_list);
    for (let i = 0; i < td_list.length; i++){
      if (td_list[i].selected){
        num ++;
        if (num == td_list.length){
          console.log(num);
          this.setData({
            allSelected: true
          });
        }
      }else{
        this.setData({
          allSelected: false
        });
      }
      for (let e = 0; e < td_list[i].count; e++) {
        if (td_list[i].list[e].selected === true && td_list[i].list[e].price){
          td.price.brandPrice += parseFloat(td_list[i].list[e].price.brandPrice);
          td.price.guidePrice += parseFloat(td_list[i].list[e].price.guidePrice);
          td.price.marketPriceSh += parseFloat(td_list[i].list[e].price.marketPriceSh);
        }
      }
    }

    td.price.brandPrice = td.price.brandPrice.toFixed(2);
    td.price.guidePrice = td.price.guidePrice.toFixed(2);
    td.price.marketPriceSh = td.price.marketPriceSh.toFixed(2);
    
    this.setData({
      price: td.price
    });
  },

  /**
   * @explain 删除
   * @param  thirdCookie 用户标识
   * @param  id_list 删除的数组id（JSON）
   * 
   * **/ 
  deleteShopCar(e){
    let _this = this, td = this.data,
        delete_shop = [], 
        arr = e.currentTarget.dataset.arr;
        console.log();
    for(let i = 0;i < arr.length; i++){
      if (arr[i].selected == true){
        delete_shop.push(arr[i].id);

      }
    }
    if (delete_shop.length > 0){
      wx.showModal({
        title: "提示",
        content: "确定要删除吗",
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: "删除中...",
              mask: true
            });
            SERVICE.POST(SERVICE.URL.deleteShopCar, {
              thirdCookie: wx.getStorageSync("thirdCookie"),
              id_list: JSON.stringify(delete_shop)
            }, (status, res) => {
              wx.hideLoading();
              if (res.data.status == "success") {
                td.price.brandPrice = 0;
                td.price.guidePrice = 0;
                td.price.marketPriceSh = 0;
                _this.setData({
                  allSelected: false,
                  price: td.price
                });
                _this.getPartsList();
              } else {
                wx.showToast({
                  title: "删除失败",
                  icon: "none",
                  mask: true
                });
              }
            });
          }
        }
      })
    }
  },


  /**
   * @explain 提交订单
   * 
   * **/ 
  submit(e){
    let td = this.data, 
        td_list = this.data.list,
        list_id = [];

    for (let i = 0; i < td_list.length; i++) {
      for (let e = 0; e < td_list[i].count; e++) {
        if (td_list[i].list[e].selected === true && td_list[i].list[e].price) {
          list_id.push(td_list[i].list[e].id);

        }
      }
    }
    this.createOrder(list_id);
  },

  /**
   * @explain 创建订单
   * @param   thirdCookie 用户标识
   * @param   add_list  id数组
   * **/ 
  createOrder(list){
    if(list.length > 0){
      let _this = this, td = this.data;
      wx.showLoading({
        title: "提交中...",
        mask: true
      });
      SERVICE.POST(SERVICE.URL.createOrder, {
        thirdCookie: wx.getStorageSync("thirdCookie"),
        add_list: JSON.stringify(list),
      }, (status, res) => {
        wx.hideLoading();
        if (res.data.status === "success") {
          if (td.isOpenRegDialog === false){
            _this.setData({
              showRegDialog: true,
              isOpenRegDialog: true
            });
            
          } else{
            wx.navigateTo({
              url: "../order/order",
            });
          }
        } else {
          wx.showToast({
            title: "提交失败",
          })
        }
      });
    }
  },

  /**
   * @explain quit 退出模板事件
   * 
   * **/ 
  quit(){
    this.setData({
      showRegDialog: false
    });
  },
  // getImgSrc(e){
  //   let imgSrc = e.currentTarget.dataset.src;
  //   console.log();
  //   wx.previewImage({
  //     urls: [imgSrc],
  //   });
  // }
});

